;(function($){
	$.fn.fcselect=function(options){
		var defaults = {
            target: 'body',         //在指定dom内创建，某些情况下滚动框架在div元素中，需自定义
            placeholder:'请选择',
            multiple:false,
            size:'normal',          // 大小 large | normal | small
			titleEventType: 'click',
			optionEventType: 'click',
			setMaxOptionNum: 8,
			optionsHoverStyle: 'newOptions_hover',
            zIndex:500,
			change: function(){},
			close: function(){},
			mutiConfEvent:function(){}
		};
		
		var options = $.extend(defaults,options);
		console.log(options)

		var _this = this,
	        CLASS_NAME = '.fc-select';

	    console.log(_this)

	    init();
        //初始化
        function init() {
            // console.log(this.options)
            CLASS_NAME = _this;
            $(CLASS_NAME).hide();

            if(options.multiple){
                multiple();
            }else{
                single();
            }
            listen();
        };

        //监听事件
        function listen() {
            var that = _this;
            var FC = $(_this).next('.fc-select-box');
            FC.off('click').on('click',function(){
                var _h = $(this).height(),      //select高
                    _w = $(this).width(),       //select宽
                    _t = $(this).offset().top,  //select距离页面top值
                    _l = $(this).offset().left; //select距离页面left值

                if($(this).attr('disabled')){
                    return false;
                }
                if($(this).hasClass('is-focus')){
                    close();
                    return false;
                }

                var id = $(this).data('id');//当前select的id
                var selected = $(this).find('input').val();

                var isCurrent = $('.fc-select-dropdown[data-id="'+id+'"]').length;//当前点击的select是否已显示下拉框
                $(this).addClass('is-focus');
                if(isCurrent == 0) {
                    create($(this),_h,_w,_t,_l,id,selected);  
                }
                // that.close();
                var otherSelect = $('.fc-select-box:not([data-id="'+id+'"])');//其他select元素
                otherSelect.removeClass('is-focus');

                var ot = $('.fc-select-dropdown:not([data-id="'+id+'"])')
                ot.addClass('fc-select-dropdown-out');
                setTimeout(function(){
                   ot.remove();
                   f =true
                },300)
            })

            //失去焦点
            $(document).on('click',function(e){
                if($('.fc-select-dropdown').length > 0) {
                    if($(e.target).parents('.fc-select-dropdown').length<1 && $(e.target).parents('.fc-select-box').length==0){
                        close();
                    }
                }
            })

            // 可清空单选
            var FCCLEARABLE = $(_this).next('.fc-select-box[clearable]');
            FCCLEARABLE.hover(function(){
                var val = $(this).find('input').val();
                if(val != ''){
                    $(this).find('.arrow').hide();
                    $(this).append('<i class="close"></i>');
                    clearAble();
                }
            },function(){
                $(this).find('.arrow').show();
                $(this).find('.close').remove();
            })
            function clearAble(){
                FCCLEARABLE.find('i.close').click(function(event){
                    event.stopPropagation();
                    var id = $(this).parent().data('id');
                    $('.fc-select-dropdown[data-id="'+id+'"]').find('li').removeClass('selected');
                    $(this).siblings('input').attr('value','');
                    that.callback($(this).parent());
                    return false; 
                })
            }
        };

        //动态生成结构
        function create(ele,_h,_w,_t,_l,id,selected) {
            var that = this;
            var data = options.data;
            var multiple = options.multiple;
            var _list = '';
            var _top = _h+_t+3;//默认下拉层显示top位置
            var animationIn = 'fc-select-dropdown-in';//进入动画,默认
            var placement = 'top-start';//下拉层初始显示位置
            var zIndex = options.zIndex;
            //data提供数据
            if(data) {
                data.map(function(d){
                    if(d.label == selected) {
                        _list+='<li data-value="'+d.value+'" class="selected">'+d.label+'</li>';
                    }else if(!selected){
                        _list+='<li data-value="'+d.value+'" class="'+(d.selected?"selected":"")+' '+(d.disabled?"disabled":"")+'">'+d.label+'</li>';
                    }else{
                        _list+='<li data-value="'+d.value+'" class="'+(d.disabled?"disabled":"")+'">'+d.label+'</li>';
                    }
                })
            }else{
                ele.prev().find('option').each(function(i,d){
                    var v = $(d).val(),
                        c = $(d).html(),
                        disabled = d.disabled;
                    if(c == selected){
                        _list+='<li data-value="'+v+'" class="selected">'+c+'</li>';
                    }else{
                        _list+='<li data-value="'+v+'" class="'+(disabled?"disabled":"")+'">'+c+'</li>';
                    }
                })
            }

            // 判断页面高度是否足够显示下拉框，如不够，在元素上层显示
            var windowHeight = $(window).height();
            var dropdownHeight = 234;//下拉框最大高度，css中设置了224，再加上padding值，超过了会显示滚动条
            if($(_list).length*32+10 < 234){    //计算生成的option总高度，32是在css中设置的li高度，加上padding值
                dropdownHeight = $(_list).length*32+10;
            }
            if(_t+_h+dropdownHeight+3 > windowHeight){
                _top = _t-dropdownHeight-4;
                placement = 'bottom-start';
            }

            var _dropdown = '<div class="fc-select-dropdown '+animationIn+'" data-id="'+id+'" '+(multiple?"multiple":"single")+' style="top:'+_top+'px;left:'+_l+'px;width:'+_w+'px;z-index:'+zIndex+'" placement="'+placement+'">'+
                '   <div class="fc-select-dropdown-scroll">'+
                '       <ul>'+_list+'</ul>'+
                '   </div>'+
                '</div>';
            $('body').append(_dropdown);

            // 多选根据是否已选内容，在下拉框中标记
            if(multiple) {
                // console.log(data)
                $('.fc-select-dropdown[data-id="'+id+'"]').find('li').removeClass('selected');
                var arr = ele.find('input:hidden').val().split(',');
                arr.map(function(d){
                    $('.fc-select-dropdown[data-id="'+id+'"]').find('[data-value="'+d+'"]').addClass('selected');
                })
            }

            var dom = $('.fc-select-dropdown[data-id="'+id+'"]');
            setTimeout(function(){
               dom.removeClass('fc-select-dropdown-in'); 
            },300)

            //页面滚动时候进行差值计算，固定在当前位置
            var target = options.target;
            var oldTop = $(target).scrollTop();
            var oldLeft = $(target).scrollLeft();
            $(target).scroll(function() {
                var left = $(target).scrollLeft();
                var top = $(target).scrollTop();
                var h = ele.height();
                if(dom.is("[placement='top-start']")){
                    dom.css({top:(h+_t+3-top+oldTop)+'px',left:(_l+oldLeft-left)+'px'})
                }else{
                    dom.css({top:_t-top+oldTop-dropdownHeight-4,left:(_l+oldLeft-left)+'px'})
                }
            })
            change(ele,dom);
        };

        //单选
        function single() {
            var that = this;
            var data = options.data;
            var value = "";  //默认选择的项

            // console.log(data)
            $(CLASS_NAME).each(function(i,elem){
                // console.log(i,elem)
                var radom = Math.ceil(Math.random() * 10000000);
                var _size = $(elem).attr('size');
                var _placeholder = $(elem).attr('placeholder');
                var _disabled = $(elem).attr('disabled');
                var _clearable = $(elem).attr('clearable');

                //通过数据型或原始option结构，获取当前选择的项目
                if(data){
                    $.each(data,function(i,d){
                        // console.log(d)
                        if(d.selected){
                            value = d.label;
                            return false;
                        }
                    })
                }else{
                    var _selected = $(elem).find('[selected]');
                    value = _selected.length>0?_selected.html():"";
                }
                var _el = '<div class="fc-select-box fc-select--single" data-id="fcselect_'+radom+'" '+(_size?_size:options.size)+' '+(_disabled?_disabled:'')+' '+(_clearable!=undefined?"clearable":"")+'><input readonly="readonly" placeholder="'+(_placeholder?_placeholder:options.placeholder)+'" value="'+value+'" /><i class="arrow"></i></div>';
                if(!$(elem).next().is('.fc-select-box')){
                    $(elem).after(_el);
                }
            })
        };

        //多选
        function multiple() {
            var that = this;
            var data = options.data;

            $(CLASS_NAME).each(function(i,elem){
                var tags='';  //默认选择的项
                var valueSelected = [];//隐藏input中保存的已选内容
                // console.log(i,elem)
                var radom = Math.ceil(Math.random() * 10000000);

                // 填充tags
                if(data){
                    // 数据由data提供
                    // tags最大显示数量
                    var maxcount = that.options.maxTagCount;
                    if(maxcount) {
                        var count = 0;
                        $.each(data,function(i,d){
                            if(d.selected){
                                count++;
                                if(count <= maxcount) {
                                    tags+='<span data-value="'+d.value+'"><span>'+d.label+'</span><i></i></span>';
                                }
                                valueSelected.push(d.label);
                            }
                        })
                        if(count > maxcount) {
                            tags+='<span>+'+(count-maxcount)+'</span>';
                        }
                    }else{
                        $.each(data,function(i,d){
                            if(d.selected){
                                tags+='<span data-value="'+d.value+'"><span>'+d.label+'</span><i></i></span>';
                                valueSelected.push(d.label);
                            }
                        })
                    }
                }else{
                    //数据由select>option提供
                    var maxcount = options.maxTagCount;
                    var optionList = $(elem).find('option');
                    if(maxcount) {
                        var count = 0;
                        $.each(optionList,function(i,d){
                            if($(d).attr('selected') == 'selected'){
                                count++;
                                if(count <= maxcount) {
                                    tags+='<span data-value="'+d.value+'"><span>'+d.label+'</span><i></i></span>';
                                }
                                valueSelected.push($(d).val());
                            }
                        })
                        if(count > maxcount) {
                            tags+='<span>+'+(count-maxcount)+'</span>';
                        }
                    }else{
                        $.each(optionList,function(i,d){
                            if($(d).attr('selected') == 'selected'){
                                tags+='<span data-value="'+d.value+'"><span>'+d.label+'</span><i></i></span>';
                                valueSelected.push(d.label);
                            }
                        })
                    }
                }

                var _disabled = $(elem).attr('disabled');
                var _size = $(elem).attr('size');
                var _placeholder = $(elem).attr('placeholder');

                var _el = '<div class="fc-select-box fc-select--multiple" data-id="fcselect_'+radom+'" '+(_size?_size:options.size)+' '+(_disabled?_disabled:'')+'><input type="hidden" value="'+valueSelected+'"><div class="fc-select-tags">'+tags+'</div><input readonly="readonly" placeholder="'+(_placeholder?_placeholder:options.placeholder)+'" /><i class="arrow"></i></div>';

                if(!$(elem).next().is('.fc-select-box')){
                    $(elem).after(_el);
                }

                // 当有多个tags时候，自适应input高度
                if(tags != '') {
                    $(elem).next().find('input:visible').attr('placeholder','');
                    setTimeout(function(){
                        var inputHeight = $(elem).next().find('input:visible').height();
                        var h = $(elem).next().find('.fc-select-tags').height();
                        if(h>inputHeight){
                            $(elem).next().find('input:visible').css({height:h+8+"px"});
                        }
                    },100)
                }
            })
            delTag(options.elem);
        };


        //多选删除tags中已选标签
        function delTag(elem) {
            var that = this;
            var FC = $(elem).next('.fc-select-box').find('.fc-select-tags span[data-value] i');
            FC.off().on('click',function(){
                var box = $(this).parents('.fc-select-box');
                var id = box.data('id');
                var value = $(this).siblings('span').html();
                var dom = $('.fc-select-dropdown[data-id="'+id+'"]');
                var tagsBox = $(this).parents('.fc-select-tags');
                var input = tagsBox.next();
                var hideInput = tagsBox.prev('input');

                // 获取input中已存的数组
                var inputArr = hideInput.val().split(',');
                inputArr.splice(jQuery.inArray(value,inputArr),1);
                hideInput.val(inputArr);

                var maxTagCount = options.maxTagCount;
                if(maxTagCount) {
                    // 设置了显示最大数量
                    tagsBox.html('');
                    if(inputArr.length > maxTagCount){
                        // 已选数组大于 maxTagCount 设置的数量
                        for(i=1;i<=maxTagCount;i++) {
                            tagsBox.append('<span data-value="'+inputArr[i-1]+'"><span>'+inputArr[i-1]+'</span><i></i></span>');
                        }
                        tagsBox.append('<span>+'+(inputArr.length-maxTagCount)+'</span>');
                    }else if(inputArr.length > 1){
                        for(i=1;i<=maxTagCount;i++) {
                            tagsBox.append('<span data-value="'+inputArr[i-1]+'"><span>'+inputArr[i-1]+'</span><i></i></span>');
                        }
                    }else if(inputArr.length > 0){
                        tagsBox.append('<span data-value="'+inputArr[0]+'"><span>'+inputArr[0]+'</span><i></i></span>');
                    }
                    that.delTag(elem)
                }else{
                    // 未设置最大显示数量，动态删除tags
                    $(this).parent().remove();
                }

                // 控制 input 高度
                var tagsHeight = box.find('.fc-select-tags').height();
                if(tagsHeight > 44) {
                    input.css({height:tagsHeight+8+"px"})
                }else{
                    input.css({height:"initial"})
                }

                // 下拉框位置动态调整
                if(dom.length > 0){
                    var inputTop = input.offset().top;
                    var inputHeight = input.height();
                    if(dom.is("[placement='top-start']")){
                        dom.css({top:inputTop+inputHeight+5+"px"});
                    }
                }

                // 移除所有tag后，显示placholder
                if(box.find('.fc-select-tags > span').length == 0) {
                    box.find('input').attr('placeholder',that.options.placeholder);
                }

                if(dom.length > 0){
                    $('.fc-select-dropdown[data-id="'+id+'"]').find('li[data-value="'+value+'"]').removeClass('selected');
                }

                // 已选内容回调
                var arr = [];
                box.find('.fc-select-tags > span').each(function(i,d){
                    arr.push($(d).data('value'));
                })
                callback(box,arr);
                return false;
            })
        };        

        //改变值
        function change(ele,dom) {
            var that = this;
            var domTop = dom.offset().top;
            if(options.multiple){
                //多选
                dom.find('ul li').off().on('click',function(){
                    var v = $(this).data('value');
                    var c = $(this).html();

                    // 有禁用选项
                    if($(this).hasClass('disabled')){
                        return false;
                    }

                    var inputArr = [];
                    if(ele.find('input:hidden').val() != '') {
                        inputArr = ele.find('input:hidden').val().split(',');
                    }
                    var maxTagCount = options.maxTagCount;
                    if(maxTagCount) {
                        // 设置了显示最大数量
                        if($(this).hasClass('selected')) {
                            $(this).removeClass('selected');
                            inputArr.splice(jQuery.inArray(v,inputArr),1);
                        }else{
                            $(this).addClass('selected');
                            inputArr.push(v);
                        }
                        ele.find('.fc-select-tags').html('');
                        if(inputArr.length > maxTagCount){
                            // 已选数组大于 maxTagCount 设置的数量
                            for(i=1;i<=maxTagCount;i++) {
                                ele.find('.fc-select-tags').append('<span data-value="'+inputArr[i-1]+'"><span>'+inputArr[i-1]+'</span><i></i></span>');
                            }
                            ele.find('.fc-select-tags').append('<span>+'+(inputArr.length-maxTagCount)+'</span>');
                        }else if(inputArr.length > 1){
                            for(i=1;i<=maxTagCount;i++) {
                                ele.find('.fc-select-tags').append('<span data-value="'+inputArr[i-1]+'"><span>'+inputArr[i-1]+'</span><i></i></span>');
                            }
                        }else if(inputArr.length > 0){
                            ele.find('.fc-select-tags').append('<span data-value="'+inputArr[0]+'"><span>'+inputArr[0]+'</span><i></i></span>');
                        }
                    }else{
                        // 未设置最大显示数量，动态添加tags
                        if($(this).hasClass('selected')) {
                            $(this).removeClass('selected');
                            ele.find('.fc-select-tags [data-value="'+v+'"]').remove();
                            inputArr.splice(jQuery.inArray(v,inputArr),1);
                        }else{
                            $(this).addClass('selected');
                            ele.find('.fc-select-tags').append('<span data-value="'+v+'"><span>'+c+'</span><i></i></span>');
                            inputArr.push(v);
                        }
                    }
                    ele.find('input:hidden').val(inputArr)

                    // 控制 input 高度
                    var tagsHeight = ele.find('.fc-select-tags').height();
                    if(tagsHeight > 44) {
                        ele.find('input:visible').css({height:tagsHeight+8+"px"})
                    }else{
                        ele.find('input:visible').css({height:"initial"})
                    }

                    // 下拉框位置动态调整
                    var inputTop = ele.find('input:visible').offset().top;
                    var inputHeight = ele.find('input:visible').height();
                    if(dom.is("[placement='top-start']")){
                        dom.css({top:inputTop+inputHeight+5+"px"});
                    }

                    // 控制input中placeholder显示
                    if(ele.find('.fc-select-tags > span').length > 0) {
                        ele.find('input:visible').attr('placeholder','');
                    }else{
                        ele.find('input:visible').attr('placeholder',options.placeholder);
                    }

                    // 已选内容回调
                    callback(ele,inputArr);
                    // 绑定多选删除tags事件
                    delTag(options.elem);
                })
            }else{
                // 单选
                dom.find('ul li').on('click',function(){
                    var v = $(this).data('value');
                    var c = $(this).html();
                    // 有禁用选项
                    if($(this).hasClass('disabled')){
                        return false;
                    }
                    $(this).addClass('selected');
                    // ele.find('input').val(c);
                    ele.find('input').attr('value',c);
                    close();
                    callback(ele,v,c);
                })
            }
        };

        //关闭
        function close() {
            var _dropdown = $('.fc-select-dropdown:not(.fc-select-dropdown-in)');
            $('.fc-select-box.is-focus').removeClass('is-focus');
            _dropdown.addClass('fc-select-dropdown-out');
            setTimeout(function(){
               _dropdown.remove(); 
            },300)

            if(options.multiple) {
                // console.log('close')
            }
            return options.close({
                // elem:id,
                value:"",
            })
        };

        //回调
        function callback(ele,v,c) {
            return options.change({
                elem:ele,
                value:v,
                label:c
            })
        };

		this.each(function(){
			var _tDom = this,_t = $(_tDom);

			options.mutiConfEvent.call(_tDom);
		})

	};
})(jQuery);
